import 'package:flutter/material.dart';

import 'package:file_picker/file_picker.dart';
import 'package:icons_plus/icons_plus.dart';
import 'package:super_study_language_tools/tools/tools_common.dart';

import '../model/model_user_album.dart';
import '../service/service_user_album.dart';
import 'page_album_media_list.dart';

class PageAlbumList extends StatefulWidget {
  const PageAlbumList({super.key});

  @override
  State<PageAlbumList> createState() => _PageAlbumListState();
}

class _PageAlbumListState extends State<PageAlbumList> {
  int _listType = 0;

  int _allQty = 0;
  int _needReviewQty = 0;
  int _studingQty = 0;

  TextStyle _selListTextStyle = new TextStyle(color: Colors.blue);
  TextStyle _normalListTextStyle = new TextStyle(color: Colors.grey);

  List<ModelUserAlbum> _list = [];

  var _sortCol = 0;

  @override
  void initState() {
    super.initState();

    op_refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[300],
        appBar: AppBar(
          backgroundColor: Colors.grey[300],
          title: Text("本地专辑列表"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.refresh),
              onPressed: () {
                op("op_refresh");
              },
            ),
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                op("op_add");
              },
            ),
          ],
        ),
        body: Column(
          children: [buildTabs(), buildTable()],
        ));
  }

  Row buildTabs() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextButton(
          child: Text(
            "所有 ${_allQty}",
            style: _listType == 0 ? _selListTextStyle : _normalListTextStyle,
          ),
          onPressed: () {
            _listType = 0;
            setState(() {});
          },
        ),
        TextButton(
            child: Text(
              "需要复习 ${_needReviewQty}",
              style: _listType == 1 ? _selListTextStyle : _normalListTextStyle,
            ),
            onPressed: () {
              _listType = 1;
              setState(() {});
            }),
        TextButton(
            child: Text(
              "最近学习  ${_studingQty}",
              style: _listType == 2 ? _selListTextStyle : _normalListTextStyle,
            ),
            onPressed: () {
              _listType = 2;
              setState(() {});
            }),
      ],
    );
  }

  buildTable() {
    // 得到当前屏幕宽度
    var screenWidth = MediaQuery.of(context).size.width;
    print("screenWidth=${screenWidth}");
    if(screenWidth<800)
      {
        return Expanded(
          child: SingleChildScrollView(
            child: DataTable(
                sortColumnIndex: _sortCol,
                sortAscending: true,
                columns: [
                  DataColumn(
                    label: Text("名字"),
                    onSort: (a, b) {
                      print("onSort:${a},${b}");
                      _sortCol = a;
                      setState(() {});
                    },
                  ),
                  // DataColumn(
                  //     label: Text("媒体数"),
                  //     onSort: (a, b) {
                  //       print("onSort:${a},${b}");
                  //       _sortCol = a;
                  //       setState(() {});
                  //     }),
                  // DataColumn(label: Text("完成数")),
                  // DataColumn(label: Text("单词量")),
                  // DataColumn(label: Text("待复习")),
                  // DataColumn(label: Text("总句子数")),
                  // DataColumn(label: Text("语速")),
                  DataColumn(label: Text("操作")),
                ],
                rows: _list
                    .map((album) =>
                    DataRow(cells: [
                      DataCell(Text(album.name!)),
                      // DataCell(Text("${album.mediaQty}")),
                      // DataCell(Text("${album.finishQty}")),
                      // DataCell(Text("${album.wordQty}")),
                      // DataCell(Text("${album.reviewQty}")),
                      // DataCell(Text("${album.sentenceQty}")),
                      // DataCell(Text("${album.speed}")),
                      DataCell(Row(
                        children: [
                          IconButton(
                            onPressed: () {
                              op("op_study", album.id!);
                            },
                            icon: Icon(Bootstrap.book),
                            tooltip: "开始学习",
                          ),
                          IconButton(
                            onPressed: () {
                              op("op_resel_folder", album.id!);
                            },
                            icon: Icon(Bootstrap.folder),
                            tooltip: "重新选择文件夹",
                          ),
                          IconButton(
                            onPressed: () {
                              op("op_del", album.id!);
                            },
                            icon: Icon(Icons.delete),
                            tooltip: "删除",
                          ),
                        ],
                      ))
                    ]))
                    .toList()),
          ),
        );
      }
    else {
      return Expanded(
        child: SingleChildScrollView(
          child: DataTable(
              sortColumnIndex: _sortCol,
              sortAscending: true,
              columns: [
                DataColumn(
                  label: Text("名字"),
                  onSort: (a, b) {
                    print("onSort:${a},${b}");
                    _sortCol = a;
                    setState(() {});
                  },
                ),
                DataColumn(
                    label: Text("媒体数"),
                    onSort: (a, b) {
                      print("onSort:${a},${b}");
                      _sortCol = a;
                      setState(() {});
                    }),
                DataColumn(label: Text("完成数")),
                DataColumn(label: Text("单词量")),
                DataColumn(label: Text("待复习")),
                DataColumn(label: Text("总句子数")),
                DataColumn(label: Text("语速")),
                DataColumn(label: Text("操作")),
              ],
              rows: _list
                  .map((album) =>
                  DataRow(cells: [
                    DataCell(Text(album.name!)),
                    DataCell(Text("${album.mediaQty}")),
                    DataCell(Text("${album.finishQty}")),
                    DataCell(Text("${album.wordQty}")),
                    DataCell(Text("${album.reviewQty}")),
                    DataCell(Text("${album.sentenceQty}")),
                    DataCell(Text("${album.speed}")),
                    DataCell(Row(
                      children: [
                        IconButton(
                          onPressed: () {
                            op("op_study", album.id!);
                          },
                          icon: Icon(Bootstrap.book),
                          tooltip: "开始学习",
                        ),
                        IconButton(
                          onPressed: () {
                            op("op_resel_folder", album.id!);
                          },
                          icon: Icon(Bootstrap.folder),
                          tooltip: "重新选择文件夹",
                        ),
                        IconButton(
                          onPressed: () {
                            op("op_del", album.id!);
                          },
                          icon: Icon(Icons.delete),
                          tooltip: "删除",
                        ),
                      ],
                    ))
                  ]))
                  .toList()),
        ),
      );
    }
  }

  void op(String s, [dynamic data]) {
    switch (s) {
      case "op_add":
        op_add();
        break;
      case "op_refresh":
        op_refresh();
        break;
      case "op_study":
        op_study(data);
        break;
      case "op_resel_folder":
        op_resel_folder(data);
        break;
      case "op_del":
        op_del(data);
        break;
    }
  }

  void op_add() {
    print("op_add() 添加媒体");
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("添加文件说明"),
            content: Text("1. 选择包含媒体文件的文件夹进行添加.\n2. 文件夹内应包含媒体文件(MP4、MP3)和字幕文件(.srt)\n"),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消添加")),
              TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop();
                    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
                    if (selectedDirectory != null) {
                      print(selectedDirectory);
                      ServiceUserAlbum.add(selectedDirectory);
                      Future.delayed(Duration(milliseconds: 500), () {
                        // 延迟执行的代码
                        op_refresh();
                      });
                    }
                  },
                  child: Text("确认添加"))
            ],
          );
        });
  }

  void op_refresh() {
    print("op_refresh() 刷新列表");

    // 1. 请求网络接口

    // 2. 读取数据库信息
    ServiceUserAlbum.list().then((v) {
      _list = v;
      setState(() {});
    });
  }

  void op_study(int id) {
    print("${id}");
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return PageAlbumMediaList(
        albumId: id,
      );
    }));
  }

  Future<void> op_resel_folder(int id) async {
    print("op_resel_folder()重新选择文件夹");
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
    if (selectedDirectory != null) {
      // User canceled the picker
      print(selectedDirectory);
      ServiceUserAlbum.updateUserAlbumPath(id, selectedDirectory).then((v) {
        op_refresh();
      });
      // Future.delayed(Duration(milliseconds: 500), () {
      //   // 延迟执行的代码
      //   // refreshAlbums();
      //   op_refresh();
      // });
    }
  }

  void op_del(int id) {
    print("op_del()删除专辑");
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("删除说明"),
            content: Text("删除专辑后相关学习记录也会被删除。"),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消删除")),
              TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop();
                    ServiceUserAlbum.deleteById(id).then((v) {
                      op_refresh();
                    });
                  },
                  child: Text("确认删除"))
            ],
          );
        });
  }
}
